package com.app.couponsharelife.ui.main.me.label

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.UserTagBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.UserLabelAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_user_label.*
import java.util.HashMap

class UserLabelActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_user_label

    private var mViewModel: MeViewModel? = null

    override fun initViews() {
        tvBack.setOnClickListener { saveTag() }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = UserLabelAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {

            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.getAllTag()!!.hasObservers()) {
            mViewModel!!.getAllTag()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetAllTag(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetAllTag(hashMapOf(), false)
                        handleError(parseErrorDate("数据出错啦"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetAllTag(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("获取失败"))
                        }
                    }
                }
            })
            mViewModel!!.saveTag()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSaveTag(hashMapOf(), false)
                        showToastMsg(it.error!!.message)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSaveTag(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSaveTag(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            showToastMsg("保存成功")
                            finish()
                        } else {
                            showToastMsg("保存失败")
                        }
                    }
                }
            })
        }
        getAllTag()
    }

    private fun handleContent(data: List<UserTagBean>) {
        if (data.isNotEmpty()) {
            (mRecyclerView.adapter as UserLabelAdapter).setData(data)
        } else {
            handleError(parseErrorDate("暂无标签"))
        }
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if ((mRecyclerView.adapter as UserLabelAdapter).list[0] is PageTipBean) {
            ((mRecyclerView.adapter as UserLabelAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
            ((mRecyclerView.adapter as UserLabelAdapter).list[0] as PageTipBean).status = pageTipBean.status
            ((mRecyclerView.adapter as UserLabelAdapter).list[0] as PageTipBean).src = pageTipBean.src
            (mRecyclerView.adapter as UserLabelAdapter).notifyItemChanged(0)
        }
    }

    private fun getAllTag() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.freshGetAllTag(map, true)
    }

    private fun saveTag() {
        val sb = StringBuilder()
        sb.append("[")
        for (item in (mRecyclerView.adapter as UserLabelAdapter).list) {
            if (item is UserTagBean) {
                for (tag in item.sons) {
                    if (tag.checked != null && tag.checked!!) {
                        sb.append("${tag.id},")
                    }
                }
            }
        }
        if (sb.toString() == "[") {
            finish()
            return
        }
        println(sb.toString())
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["tagids"] = sb.toString().substring(0, sb.toString().length - 1) + "]"
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshSaveTag(map, true)
    }
}
